﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Siva.CBC.Barnacle.ashx
{
    /// <summary>
    /// downRecordHandler 的摘要说明
    /// </summary>
    public class downRecordHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string filepath = context.Request.QueryString["file"];

            if (File.Exists(filepath))
            {
                FileInfo f = new FileInfo(filepath);
                // 设置响应类型为音频文件的MIME类型
                context.Response.ContentType = "audio/mpeg";

                // 设置内容处置为附件，以触发下载
                context.Response.AddHeader("Content-Disposition", "attachment; filename="+f.Name);

                // 打开文件并写入响应流
                FileStream fileStream = new FileStream(filepath, FileMode.Open);
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    context.Response.OutputStream.Write(buffer, 0, bytesRead);
                }

                fileStream.Close();

                //此次操作写入日志
                string sql = "insert into downrecordlogs(fullname,IP) values(?fullnameValue,?IPValue)";
                MySql.Data.MySqlClient.MySqlParameter[] para = new MySql.Data.MySqlClient.MySqlParameter[]
                {
                    new MySql.Data.MySqlClient.MySqlParameter("?fullnameValue",MySql.Data.MySqlClient.MySqlDbType.VarString){ Value=filepath},
                    new MySql.Data.MySqlClient.MySqlParameter("?IPValue",MySql.Data.MySqlClient.MySqlDbType.VarString){Value=context.Request.ServerVariables["REMOTE_ADDR"]}
                };
                int result = SqlHelper.ExecuteNonQuery(sql, para);
            }
            else
            {
                context.Response.Write("文件不存在，请联系管理员");
            }

            //context.Response.Write(filepath);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}